package com.jonychen.swagger2demo.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class PropertiesUtil {
	private static Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
	private static Properties properties;

	static {
		properties = new Properties();
		ClassLoader loader = PropertiesUtil.class.getClassLoader();
		try {
			InputStream in = loader.getResourceAsStream("redis-config.properties");
			properties.load(in);
			in.close();
		} catch (FileNotFoundException e) {
			log.error("未找到配置文件",e);
		} catch (IOException e) {
			log.error("读取配置文件异常",e);
		}
	}

	public static Properties getProperties() {
		return properties;
	}

	public static Integer getIntegerValue(String key) {
		return Integer.parseInt(properties.getProperty(key));
	}

	public static String getStringValue(String key) {
		return properties.getProperty(key);
	}

	public static boolean getBooleanValue(String key) {
		return Boolean.parseBoolean(properties.getProperty(key));
	}

	public static Object getValue(String key) {
		return properties.getProperty(key);
	}


	/**
	 * 获取utf-8
	 * @param key
	 * @return
	 */
	public static String getStringValue2(String key) {
		String result = properties.getProperty(key);
		try {
			//这一句是重点
			result=new String(result.getBytes("ISO-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("获取配置文件内容转换为utf-8异常",e);
			return null;
		}
		return result;
	}

	public static String getValueFromFile(String fileName, String key) throws IOException {
		Properties properties = new Properties();
		InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
		properties.load(in);
		return properties.getProperty(key);
	}

	public static void main(String[] args) {
		String stringValue = getStringValue2("redis.address");
		System.out.println(stringValue);
	}
}
